# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from Tkinter import *
from time import sleep
from HttpClient import HttpClient
import json,io
from multiprocessing import Process
import multiprocessing
from PIL import Image
class WebQQ(HttpClient):
    def __init__(self):
        self.__cookie = ""
        self.__ptwebqq = ""
        self.__vfwebqq = ""
        self.__psessionid = ""
        self.__hash = ""
        self.__uin = ""

        self.__root = ""
        self.queue = multiprocessing.Queue()

    #获取二维码
    def __QRCode(self):
        img = self.Get(url="https://ssl.ptlogin2.qq.com/ptqrshow?appid=501004106&e=0&l=M&s=5&d=72&v=4")
        if img!=None:
            data_stream = io.BytesIO(img)
            imgfile = Image.open(data_stream)
            imgfile.save('1.jpg')
            self.__QRLogin()
            return True
        else:
            print(u"二维码下载失败")
            return False

    #检测扫码状态，登录进度
    def __QRLogin(self):
        res = self.Get("https://ssl.ptlogin2.qq.com/ptqrlogin?webqq_type=10&remember_uin=1"+
                       "&login2qq=1&aid=501004106&u1=http%3A%2F%2Fw.qq.com%2Fproxy.html%3Flogin2qq%3D1%26webqq_type%3D10"+
                       "&ptredirect=0&ptlang=2052&daid=164&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=0-0-136435"+
                       "&mibao_css=m_webqq&t=undefined&g=1&js_type=0&js_ver=10139&login_sig=&pt_randsalt=0",
                       "https://ui.ptlogin2.qq.com/cgi-bin/login")
        if "登录成功" not in res:
            sleep(1)
            print(u"jin kuai sao miao")
            return self.__QRLogin()
        else:
            res = res.decode("UTF-8")
            return self.__check_sig(res[res.find("http"):res.find(u"','0','登录成功！'")].encode())

    #获得ptwebqq  cookie
    def __check_sig(self,url):
        res = self.Get(url=url,refer="https://ui.ptlogin2.qq.com/cgi-bin/login")
        if res!=None:
            self.__ptwebqq = self.getCookie("ptwebqq")
            self.__getvfwebqq()
            return self.__login2()
        else:
            return False
    #获得vfwebqq  cookie
    def __getvfwebqq(self):
        res = self.Get(url="http://s.web2.qq.com/api/getvfwebqq?ptwebqq="+self.__ptwebqq+"&clientid=53999199&psessionid=",refer="http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1")
        if res!=None:
            jsn = json.loads(res)
            self.__vfwebqq = jsn["result"]["vfwebqq"]

    #登录 获取uin psessionid
    def __login2(self):
        data = "r=%7B%22ptwebqq%22%3A%22"+self.__ptwebqq+"%22%2C%22clientid%22%3A53999199%2C%22psessionid%22%3A%22%22%2C%22status%22%3A%22online%22%7D"
        res = self.Post(url = "http://d1.web2.qq.com/channel/login2",data = data.encode(encoding="utf8"),refer = "http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=2")
        if len(res)==0:
            return False
        jsn = json.loads(res)
        if jsn["retcode"]==0:
            self.__uin = jsn["result"]["uin"]
            self.__psessionid = jsn["result"]["psessionid"]
            return True
        else:
            return False

    #好友的hash  参考HexBlog
    def __friendsHash(self,uin,pt):
        N=[0 for x in range(4)]
        V=[0 for x in range(4)]
        U=[0 for x in range(8)]
        #字符串转换为字符数组
        k=pt.encode(encoding="UTF8")
        n=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
        for x in range(len(k)):
            N[x%4]^=ord(k[x])
        x=int(uin)
        V[0] = x >> 24 & 255 ^ 69;
        V[1] = x >> 16 & 255 ^ 67;
        V[2] = x >> 8 & 255 ^ 79;
        V[3] = x & 255 ^ 75;
        for x in range(8):
            U[x]=(x%2==0) and N[x>>1] or V[x>>1]
        result=""
        for x in U:
            result+=n[x>>4&15]
            result+=n[x&15]
        return result

    #获取好友列表
    def __get_user_friends(self):
        self.__hash = self.__friendsHash(self.__uin,self.__ptwebqq)
        data="r=%7B%22vfwebqq%22%3A%22"+self.__vfwebqq+"%22%2C%22hash%22%3A%22"+self.__hash+"%22%7D"
        res=self.Post(url="http://s.web2.qq.com/api/get_user_friends2",
                       data=data.encode(encoding="utf8"),
                         refer="http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1")
        if len(res)!=0:
            jsn=json.loads(res)
            if jsn["retcode"]==0:
                for x in jsn["result"]["info"]:
                    print x["nick"]
    #zu xin xi
    def __get_group_name_list_mask2(self):
        data="r=%7B%22vfwebqq%22%3A%22"+self.__vfwebqq+"%22%2C%22hash%22%3A%22"+self.__hash+"%22%7D"
        res=self.Post(url="http://s.web2.qq.com/api/get_group_name_list_mask2",data=data.encode(encoding="utf8"),refer="http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1")
        if len(res)!=0:
            print res
    #hui hua lie biao
    def __get_discus_list(self):
        url='http://s.web2.qq.com/api/get_discus_list?clientid=53999199&psessionid='+self.__ptwebqq+'&vfwebqq='+self.__vfwebqq
        res = self.Get(url=url,refer="http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1")
        if len(res)!=0:
            print res
    #
    def __get_self_info2(self):
        res = self.Get(url='http://s.web2.qq.com/api/get_self_info2',refer="http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1")
        if len(res)!=0:
            print res
    #
    def __get_single_long_nick2(self,tuin):
        url='http://s.web2.qq.com/api/get_single_long_nick2?tuin=%s&vfwebqq=%s'%(tuin,self.__ptwebqq)
        res = self.Get(url=url,refer="http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1")
        if len(res)!=0:
            print res
    #
    def __get_friend_uin2(self,tuin):
        url='http://s.web2.qq.com/api/get_friend_uin2?tuin=%s&type=1&vfwebqq=%s'%(tuin,self.__ptwebqq)
        res = self.Get(url=url,refer="http://d.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1")
        if len(res)!=0:
            print res
    #接收消息，现在不能用了
    def __poll(self):
        data="r=%7B%22ptwebqq%22%3A%22"+self.__ptwebqq+"%22%2C%22clientid%22%3A53999199%2C%22psessionid%22%3A%22"+self.__psessionid +"%22%2C%22key%22%3A%22%22%7D"
        res=self.Post(url="http://d1.web2.qq.com/channel/poll2",data=data.encode(encoding="utf8"),refer="ttp://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2")
        if len(res)!=0:
           print res
    #
    def __send_msg(self,message):
        import urllib
        data='{"to":544797212,"content":"[\"243\",[\"font\",{\"name\":\"宋体\",\"size\":10,\"style\":[0,0,0],\"color\":\"000000\"}]]","face":537,"clientid":53999199,"msg_id":60250003,"psessionid":"'+self.__psessionid+'"}'
        to='544797212'
        content='123'
        msgid='73750001'
        #data='r='+urllib.quote(data)
        data=u'r=%7B%22to%22%3A544797212%2C%22content%22%3A%22%5B%5C%22123%5C%22%2C%5B%5C%22font%5C%22%2C%7B%5C%22name%5C%22%3A%5C%22%E5%AE%8B%E4%BD%93%5C%22%2C%5C%22size%5C%22%3A10%2C%5C%22style%5C%22%3A%5B0%2C0%2C0%5D%2C%5C%22color%5C%22%3A%5C%22000000%5C%22%7D%5D%5D%22%2C%22face%22%3A537%2C%22clientid%22%3A53999199%2C%22msg_id%22%3A83750001%2C%22psessionid%22%3A%22'+self.__psessionid+u'%22%7D'
        data=data.encode('utf8')
        print data
        res=self.Post(url="http://d1.web2.qq.com/channel/send_buddy_msg2",data=data,refer="http://d1.web2.qq.com/proxy.html?v=20151105001&callback=1&id=2")
        print res
        #{"errCode":0,"msg":"send ok"}

    def debg(self):
        self.__QRCode()
        self.__get_user_friends()
        self.__get_group_name_list_mask2()
        self.__get_discus_list()
        self.__get_self_info2()

        tuin='544797212'
        self.__get_single_long_nick2(tuin)
        self.__get_friend_uin2(tuin)
        self.__get_single_long_nick2(tuin)
        self.__get_friend_uin2(tuin)
        self.__send_msg('ert')
if  __name__ =="__main__":
    '''qq=WebQQ()
    qq.run()'''
    qq=WebQQ()
    qq.debg()
